package com.jkkc.lib.base.util.logcat

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent

/**
 * Author:LiXian
 * <p>
 * Desc:Logcat日志记录工具类
 * Version:1.0
 * date 2023/3/29 13:21
 */
const val LOGCAT_TYPE_ALL = 0
const val LOGCAT_TYPE_SINGLE = 1
const val LOGCAT_TYPE_ALL_SINGLE = 3

class LogcatObserver(var type: Int, var filePath: String) : LifecycleObserver {

    companion object {
        @JvmStatic
        @JvmOverloads
        fun getLogcatUtils(type: Int, filePath: String = "") = LogcatObserver(type, filePath)
    }

    // logcat日志记录进程id
    private var mLogcatPid: String? = ""

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
        when (type) {
            // 开始记录整个App Logcat日志
            LOGCAT_TYPE_ALL -> {
                LogcatManager.startRecordAPPLogcat(filePath)
            }

            // 开始记录单个页面 Logcat日志
            LOGCAT_TYPE_SINGLE -> {
                LogcatManager.startRecordLogcatRightNow(filePath) { pid -> mLogcatPid = pid }
            }

            // 开始记录整个App和单个页面 Logcat日志
            LOGCAT_TYPE_ALL_SINGLE -> {
                LogcatManager.startRecordAPPLogcat(filePath)
                LogcatManager.startRecordLogcatRightNow(filePath) { pid -> mLogcatPid = pid }
            }
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        when (type) {
            LOGCAT_TYPE_ALL -> {
                LogcatManager.stopAllRecord()
            }

            LOGCAT_TYPE_SINGLE -> {
                LogcatManager.stopRecordLogcat(mLogcatPid)
            }

            LOGCAT_TYPE_ALL_SINGLE -> {
                LogcatManager.stopAllRecord()
                LogcatManager.stopRecordLogcat(mLogcatPid)
            }
        }
    }
}